import {syncRouter} from './router'
import router from './router'
import store from './store'
import storage from 'store'
import {ACCESS_TOKEN} from './store/mutation-types'
import NProgress from "nprogress";
import "nprogress/nprogress.css";

const whiteList = ['login', 'register', 'registerResult', 'bindKey', 'share']
const loginRoutePath = '/user/login'

router.beforeEach((to, from, next) => {
    NProgress.start();
    if (storage.get(ACCESS_TOKEN)) {
        if (to.path === loginRoutePath) {
            next()
        } else {
            if (store.getters.userInfo === undefined || Object.keys(store.getters.userInfo).length === 0) {
                store.dispatch('GetInfo').then(async () => {
                    const addRouter = await syncRouter()
                    router.addRoute(addRouter[0])
                    next(to.fullPath)
                })
                    .catch(() => {
                        store.dispatch('Logout').then(() => {
                            next({path: loginRoutePath, query: {redirect: to.fullPath}})
                        })
                    })
            } else {
                next()
            }
        }
    } else {
        if (whiteList.includes(to.name)) {
            // 在免登录白名单，直接进入
            next()
        } else {
            next({path: loginRoutePath, query: {redirect: to.fullPath}})
        }
    }
})

router.afterEach(() => {
    NProgress.done();
});
